import java.io.*;
import java.nio.channels.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;


public class FileLocker extends JFrame{
	private String password;
	private File f;
	private BufferedReader br;



		public void lockAFile(){
			 try {
                		//Choose a File.
                		JFileChooser chooser =new  JFileChooser();
				        int returnVal = chooser.showOpenDialog(null);
				        if(returnVal == JFileChooser.APPROVE_OPTION) {
					        f = chooser.getSelectedFile();
					        br=new BufferedReader(new FileReader(f));
				        /*
	                        String st="";
					        while((st=br.readLine())!=null){
					            System.out.println(st);
					        }
				        */
				        }

                        RandomAccessFile file = new RandomAccessFile(f, "rw");
                        FileChannel fileChannel = file.getChannel();
                        FileLock fileLock = fileChannel.tryLock();
                        if (fileLock != null) {
                                System.out.println("File is locked");
                               // accessFile();
                        }
                } catch (Exception e) {
                		System.out.print(""+e.getMessage());
                }
		}



    public void unlockFile(){
		try
        {
            RandomAccessFile file = new RandomAccessFile(f, "rw");
            FileChannel fileChannel = file.getChannel();
			FileLock fileLock = null;

            //if (fileLock != null){
                System.out.println("File is released");
                fileLock.release();
           // }
        }catch (Exception ex){
        	System.out.println(""+ex.getMessage());
        }

    }


		public String getName(){
			return f.getPath();
		}






        public void accessFile() {
                try {
                    String line = "";
                    BufferedReader br = new BufferedReader(new FileReader(f));
                    while ((line = br.readLine()) != null) {
                            System.out.println(line);
                    }
                } catch (Exception e) {
                        System.out.println(e);
                }
        }




		//tester
        public static void main(String[] args) throws Exception {
               FileLocker filelock = new FileLocker();
               filelock.lockAFile();
			   filelock.unlockFile();


        }


}